package Demo1;

import java.util.Arrays;
import java.util.Comparator;

class Student implements Comparable<Student> {
    int age;
    int score;
    String name;

    //父类构造
    public Student(int age, int score, String name) {
        this.age = age;
        this.score = score;
        this.name = name;
    }

    //toString方法
    @Override
    public String toString() {
        return "Student{" +
                "age=" + age +
                ", score=" + score +
                ", name='" + name + '\'' +
                '}';
    }

    // 默认比较方法
    @Override
    public int compareTo(Student o) {
        return this.age - o.age;    //升序
    }
}

//比较器
class AgeComparator implements Comparator<Student>{

    @Override
    public int compare(Student o1, Student o2) {
        return o1.age - o2.age;
    }
}

class ScoreComparator implements Comparator<Student>{

    @Override
    public int compare(Student o1, Student o2) {
        return o1.score - o2.score;
    }
}

class NameComparator implements Comparator<Student>{

    @Override
    public int compare(Student o1, Student o2) {
        return o1.name.compareTo(o2.name);
    }
}

public class Test {
    public static void main(String[] args) {
        Student[] students = new Student[3];
        Student student1 = new Student(1, 10, "A");
        Student student2 = new Student(3, 30, "D");
        Student student3 = new Student(2, 20, "C");
        students[0] = student1;
        students[1] = student2;
        students[2] = student3;
        System.out.println(Arrays.toString(students));
        ScoreComparator scoreComparator = new ScoreComparator();
        Arrays.sort(students,scoreComparator);  //第二个传比较器，比较依据  分数比较
        System.out.println(Arrays.toString(students));
        Arrays.sort(students,new NameComparator()); //比较依据  名字比较
        System.out.println(Arrays.toString(students));
    }

    public static void main2(String[] args) {
        Student student1 = new Student(1, 40, "A");
        Student student2 = new Student(3, 30, "B");
        AgeComparator ageComparator = new AgeComparator();
        int ret = ageComparator.compare(student1,student2); //大于零，前大于后
        System.out.println("年龄比较"+ret);
        ScoreComparator scoreComparator = new ScoreComparator();
        int ret1 = scoreComparator.compare(student1,student2);
        System.out.println("分数比较"+ret1);
    }

    public static void main1(String[] args) {
        Student[] students = new Student[3];
        Student student1 = new Student(1, 10, "A");
        Student student2 = new Student(3, 30, "B");
        Student student3 = new Student(2, 20, "C");
        students[0] = student1;
        students[1] = student2;
        students[2] = student3;
        System.out.println(Arrays.toString(students));
        Arrays.sort(students);  //要提toString方法
        System.out.println(Arrays.toString(students));
    }
}

